package com.hulman.oms.service;

import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.MonthReport;
import com.hulman.oms.bean.User;
import com.hulman.oms.dao.MonthReportDao;
import com.hulman.oms.exception.IoTException;
import com.hulman.oms.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

/**
 * @Author: maxwellens
 */
@Service
public class MonthReportService
{
    @Value("${file-home}")
    private String fileHome;
    @Autowired
    private MonthReportDao monthReportDao;
    @Autowired
    private OnlyOfficeService onlyOfficeService;

    public List<MonthReport> findMonthReports(Map<String, Object> map)
    {
        return monthReportDao.findMonthReports(map);
    }

    public Integer findMonthReportsCount(Map<String, Object> map)
    {
        return monthReportDao.findMonthReportsCount(map);
    }

    public Result findMonthReportsResult(Map<String, Object> map)
    {
        Integer page = (Integer) map.get("page");
        Integer limit = (Integer) map.get("limit");
        if (page != null && limit != null)
        {
            map.put("start", (page - 1) * limit);
            map.put("length", limit);
        }
        int count = monthReportDao.findMonthReportsCount(map);
        List<MonthReport> data = monthReportDao.findMonthReports(map);
        return new Result(data, count);
    }

    public MonthReport findMonthReportById(Integer id)
    {
        return monthReportDao.findMonthReportById(id);
    }

    public void saveMonthReport(MonthReport monthReport)
    {
        if (monthReport.getId() != null && monthReport.getId() != 0)
        {
            monthReportDao.updateMonthReport(monthReport);
        } else
        {
            monthReportDao.insertMonthReport(monthReport);
        }
    }

    public void deleteMonthReportById(Integer id)
    {
        monthReportDao.deleteMonthReportById(id);
    }

    public void deleteMonthReports(int[] ids)
    {
        monthReportDao.deleteMonthReports(ids);
    }

    private void checkMonthReport(MonthReport monthReport)
    {
        Map<String, Object> map = new HashMap<>();
        map.put("year", monthReport.getYear());
        map.put("month", monthReport.getMonth());
        Integer count = monthReportDao.findMonthReportsCount(map);
        if (count > 0)
        {
            throw new IoTException("该月工作报告已生成");
        }
    }

    public void create(MonthReport monthReport) throws IOException
    {
        checkMonthReport(monthReport);
        User user = SubjectUtil.getUser();
        monthReport.setCreateById(user.getId());
        monthReport.setCreateByName(user.getName());
        int year = monthReport.getYear();
        int month = monthReport.getMonth();
        LocalDate firstDayOfMonth = LocalDate.of(year, month, 1);
        LocalDate lastDayOfMonth = firstDayOfMonth.with(TemporalAdjusters.lastDayOfMonth());
        Date startDate = Date.from(firstDayOfMonth.atStartOfDay(ZoneId.systemDefault()).toInstant());
        Date endDate = Date.from(lastDayOfMonth.atStartOfDay(ZoneId.systemDefault()).toInstant());
        monthReport.setStartDate(startDate);
        monthReport.setEndDate(endDate);
        monthReport.setState(0);
        //模板生成报告
        if (monthReport.getSource() == 1)
        {
            Map<String, Object> map = new HashMap<>();
            map.put("today", DateUtil.toChineseDate(DateUtil.now()));
            map.put("year", year);
            map.put("month", month);
            map.put("startDate", DateUtil.toChineseDate(startDate));
            map.put("endDate", DateUtil.toChineseDate(endDate));
            InputStream inputStream = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("template/month-report.docx");
            String fileId = StringUtil.uuid() + ".docx";
            Path filePath = Paths.get(fileHome, fileId);
            OutputStream outputStream = Files.newOutputStream(filePath);
            DocUtil.export(inputStream, outputStream, map);
            monthReport.setFileId(fileId);
        }
        monthReportDao.insertMonthReport(monthReport);
        String fileName = monthReport.getReportCycle() + "养护月报." + FileUtil.parseExtName(monthReport.getFileId());
        onlyOfficeService.create(monthReport.getFileId(), fileName);
    }

    public void submit(Integer id)
    {
        MonthReport monthReport = monthReportDao.findMonthReportById(id);
        monthReport.setState(1);
        monthReport.setEditDate(new Date());
        monthReportDao.updateMonthReport(monthReport);
    }

}
